package com.student.wym.interceptor;

import com.student.wym.po.Teacher;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * copy
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final String[] IGNORE_URI = {"/login"};
    private static final String TEACHER_IN_SESSION = "TEACHER_IN_SESSION";

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Teacher teacher = (Teacher) (request.getSession()).getAttribute(TEACHER_IN_SESSION);
        String url = request.getRequestURI();
        for (String s : IGNORE_URI) {
            if (url.contains(s)) {
                return true;
            }
        }
        if (teacher == null) {
            response.sendRedirect("login");
            return false;
        }
        return true;
    }

}
